package com.hitnet.hitnet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;

import com.facebook.GraphResponse;
import com.facebook.HttpMethod;

import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.apache.http.HttpStatus;
import org.json.JSONException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 登录界面,从facebook获得用户信息
 */
public class FaceBookLogin extends Activity{

    //登录按钮
	private LoginButton loginButton;

    //登录回调
	private CallbackManager callbackManager;

    //Volley 的请求队列
    private RequestQueue mQueue ;

    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Intent i = new Intent(FaceBookLogin.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(),"login failed!",Toast.LENGTH_SHORT);
                    break;

            }
            super.handleMessage(msg);
        }
    };

    @Override
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        //注册 facebook 的 sdk
		FacebookSdk.sdkInitialize(getApplicationContext());
        FacebookSdk.setIsDebugEnabled(true);

        //这段代码必须在注册之后，否则会 crash 掉
		setContentView(R.layout.facebook_login);

        //修改 title
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("Login");

        //隐藏返回按钮
        ImageView backImage = (ImageView) findViewById(R.id.comeBack);
        backImage.setVisibility(View.GONE);

        //初始化请求队列
        mQueue = Volley.newRequestQueue(getApplicationContext());

        //获得debug key用于调试，把输出的 debug key 拷贝到 facebook app 管理里面对应位置即可
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.hitnet.hitnet",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        callbackManager = CallbackManager.Factory.create();

        //TODO: 设置登录后获取信息权限，获得需要的用户信息，如 email
		loginButton = (LoginButton) findViewById(R.id.login_button);
		loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));

		// 登录回调方法
		loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                final AccessToken accessToken = loginResult.getAccessToken();

                String token = accessToken.getToken();
                String username = accessToken.getUserId();
                //getCurrentProfile()
                //Log.d("token", token);
                //Log.d("username", username);
                Log.d("expire", accessToken.getExpires().toGMTString());


                //保存token信息到本地
                Context ctx = FaceBookLogin.this;
                SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                //存入本地

                editor.putString("username", username);
                editor.putString("token", token);
                editor.commit();

                new GraphRequest(
                        accessToken,
                        "/me",
                        null,
                        HttpMethod.GET,
                        new GraphRequest.Callback() {
                            @Override
                            public void onCompleted(GraphResponse graphResponse) {
                                //String email, firstName;
                                try {
                                    String token = accessToken.getToken();
                                    String username = accessToken.getUserId();

                                    //Log.d("email", graphResponse.getJSONObject().getString("email"));
                                    //Log.d("name", graphResponse.getJSONObject().getString("first_name"));

                                    //TODO:将登录数据传到服务器
                                    Map<String, String> params = new HashMap<String, String>();
                                    params.put("username", username);
                                    params.put("token", token);
                                    params.put("email",graphResponse.getJSONObject().getString("email"));
                                    params.put("name",graphResponse.getJSONObject().getString("first_name"));
                                    //params.put()
                                    //把信息传送到服务器
                                    //postUserInfo("http://54.66.222.127:3000/login", params);
                                    postUserInfo("http://54.66.222.127:8000/login", params);

                                } catch (JSONException e) {
                                }
                                //editor.put
                            }
                        }

                ).executeAsync();


            }

            public void postUserInfo(String url, final Map<String, String> params) {

                StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("response", response);
                        if (response.compareTo("login") == 0)
                            FaceBookLogin.this.handler.sendEmptyMessage(1);  //发送消息，handler根据状态码做相应处理，1 登录成功跳转到主界面，并销毁当前界面
                        else
                            FaceBookLogin.this.handler.sendEmptyMessage(2);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse networkResponse = error.networkResponse;
                        if (networkResponse != null && networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
                            //TODO:登录失败信息，没有添加提示
                        }
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        return params;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("Content-Type", "application/x-www-form-urlencoded");
                        return params;
                    }
                };
                mQueue.add(sr);
            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Toast.makeText(getApplicationContext(), exception.toString(), Toast.LENGTH_SHORT);
            }
        });

	};

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}
